package chapter18ShareLock;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by LinGer on 2019/6/25
 */
public class User {

    private String name;
    private MyCount myCount;
    private ReadWriteLock myLock;

    User(String name, MyCount myCount){
        this.name = name;
        this.myCount = myCount;
        this.myLock = new ReentrantReadWriteLock();
    }

    public void getCash(){
        new Thread(){
            @Override
            public void run() {
                myLock.readLock().lock();
                try {
                    System.out.println(this.getName() + " getCash start");
                    myCount.getCash();
                    Thread.sleep(1);
                    System.out.println(this.getName() + " getCash end");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    myLock.readLock().unlock();
                }
            }
        }.start();
    }

    public void setCash(final int cash){
        new Thread(){
            @Override
            public void run() {
                myLock.writeLock().lock();
                try{
                    System.out.println(this.getName() + " setCash start");
                    myCount.setCash(cash);
                    Thread.sleep(1);
                    System.out.println(this.getName() + " setCash end");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    myLock.writeLock().unlock();
                }
            }
        }.start();
    }
}
